//进程间的通信-管道-父子进程通信
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h> 
int main(void)
{
    int fd[2]={0};
    if(pipe(fd)<0)//创建匿名管道失败
    {
        printf("管道创建失败\n");
        return 1;
    }
    pid_t id=fork();
    if(id==0)
    {
        close(fd[0]);//子进程负责写，父进程负责读
        char buf[64]="hello father,i am child";
        int count=10;
        while(count--)
        {
            write(fd[1],buf,strlen(buf));
            sleep(1);
        }
        exit(0);
    }
    close(fd[1]);//父进程读，关闭写通道
    char buff[64];
    while(1)
    {
        ssize_t ret=read(fd[0],buff,sizeof(buff));
        if(ret>0)
        {
            buff[ret]='\0';
            printf("Message:%s\n",buff);
        }
        else if(ret==0)
        {
            printf("Message:Over\n");
            break;
        }
        else 
        {
            printf("Message:Failed\n");
            break;
        }
    }
    waitpid(id,NULL,0);
    return 0;
}

